import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const ORGANIZATION_BASE = "/system/org/organizations";

export const ORG_TYPE_OPTIONS = [
  { label: "卖家", value: "seller" },
  { label: "买家", value: "buyer" },
  { label: "买卖一体", value: "both" }
];

export const ORG_STATUS_MAP: Record<number, string> = {
  0: "待审核",
  1: "启用",
  2: "已禁用"
};

export const ORG_STATUS_OPTIONS = [
  { label: "待审核", value: 0 },
  { label: "启用", value: 1 },
  { label: "已禁用", value: 2 }
];

export interface OrganizationFilterParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  org_type?: string;
  status?: number | string;
  region_id?: number | string;
  invited_by?: number | string;
  inviter_user_id?: number | string;
  owner_user_id?: number | string;
  ids?: Array<number>;
}

export interface OrgProfile {
  license_number?: string;
  license_photo?: string;
  tax_number?: string;
  legal_rep?: string;
  registered_capital?: string;
  biz_scope?: string;
  established_at?: string;
  extra?: Record<string, any>;
  [key: string]: any;
}

export interface OrgContact {
  contact_name?: string;
  contact_phone?: string;
  contact_email?: string;
  bank_name?: string;
  bank_account?: string;
  invoice_title?: string;
  invoice_taxno?: string;
  extra?: Record<string, any>;
  [key: string]: any;
}

export interface OrgAddress {
  id?: number;
  contact_name?: string;
  contact_phone?: string;
  province?: string;
  city?: string;
  district?: string;
  address?: string;
  postal_code?: string;
  address_type?: string;
  is_default?: number | boolean;
  [key: string]: any;
}

export interface OrganizationListItem {
  id: number;
  name: string;
  org_type: string;
  logo_url?: string | null;
  warehouse_code?: string;
  status: number;
  status_label: string;
  region_id: number | null;
  region_label: string;
  region_path: string;
  owner_user_id: number | null;
  invited_by: number | null;
  inviter_user_id: number | null;
  approved_by: number | null;
  approved_at: string | null;
  create_time?: string;
  update_time?: string;
  profile?: OrgProfile | null;
  contact?: OrgContact | null;
  addresses?: OrgAddress[];
  region?: {
    id: number;
    name: string;
    code: string;
    path?: string;
  } | null;
  extra?: Record<string, any>;
}

export type OrganizationDetail = OrganizationListItem;

export interface OrganizationListResult {
  list: OrganizationListItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
}

const mapOrganization = (item: Record<string, any>): OrganizationListItem => {
  const profile =
    item.profile && typeof item.profile === "object"
      ? { ...item.profile }
      : null;
  const contact =
    item.contact && typeof item.contact === "object"
      ? { ...item.contact }
      : null;
  const addresses = ensureArray<Record<string, any>>(item.addresses ?? []).map(
    address => ({
      ...address,
      id: toNumber(address.id, 0) || undefined,
      is_default:
        address.is_default !== undefined
          ? Number(address.is_default) === 1
          : false
    })
  );

  const rawRegion =
    item.region && typeof item.region === "object" ? item.region : null;
  const regionIdSource =
    item.region_id ?? rawRegion?.id ?? item.regionId ?? null;
  const regionId =
    regionIdSource !== null && regionIdSource !== undefined
      ? toNumber(regionIdSource, 0) || null
      : null;

  const regionName =
    rawRegion?.name ??
    item.region_name ??
    item.regionLabel ??
    item.region_label ??
    "";
  const regionCode =
    rawRegion?.code ?? item.region_code ?? item.regionCode ?? "";
  const regionPath =
    item.region_path ?? item.region_full_name ?? rawRegion?.path ?? regionName;
  const regionLabel =
    regionPath || regionName || (regionId ? `区域 ${regionId}` : "");
  const inviterIdSource =
    item.inviter_user_id ?? item.invited_by ?? item.inviterId ?? null;
  const inviterId =
    inviterIdSource !== null && inviterIdSource !== undefined
      ? toNumber(inviterIdSource, null)
      : null;
  return {
    id: toNumber(item.id, 0),
    name: item.name ?? "",
    org_type: item.org_type ?? "seller",
    logo_url: item.logo_url ?? null,
    warehouse_code: item.warehouse_code ?? "",
    status: toNumber(item.status, 0),
    status_label:
      item.status_label ?? ORG_STATUS_MAP[toNumber(item.status, 0)] ?? "",
    region_id: regionId,
    region_label: regionLabel,
    region_path: regionPath ?? "",
    owner_user_id:
      item.owner_user_id !== null && item.owner_user_id !== undefined
        ? toNumber(item.owner_user_id, null)
        : null,
    invited_by: inviterId,
    inviter_user_id: inviterId,
    approved_by:
      item.approved_by !== null ? toNumber(item.approved_by, null) : null,
    approved_at: item.approved_at ?? null,
    create_time: item.create_time ?? "",
    update_time: item.update_time ?? "",
    profile,
    contact,
    addresses,
    region: rawRegion
      ? {
          id: toNumber(rawRegion.id, 0),
          name: rawRegion.name ?? "",
          code: regionCode,
          path: regionPath ?? ""
        }
      : null,
    extra: item.extra && typeof item.extra === "object" ? { ...item.extra } : {}
  };
};

const serialiseAddresses = (addresses: OrgAddress[] = []) => {
  return addresses.map(address => ({
    ...address,
    is_default: Number(address.is_default ? 1 : 0)
  }));
};

export const fetchOrganizationList = async (
  params: OrganizationFilterParams = {}
): Promise<OrganizationListResult> => {
  const page = toNumber(params.page, 1) || 1;
  const pageSize = toNumber(params.page_size, 10) || 10;

  const res = await http.request<ApiResponse<any>>("get", ORGANIZATION_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data ?? {}) as Record<string, any>;
  const list = ensureArray<Record<string, any>>(
    payload.list ?? payload.data ?? []
  ).map(mapOrganization);
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination
  };
};

export const fetchOrganizationDetail = async (
  id: number | string
): Promise<OrganizationDetail> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${ORGANIZATION_BASE}/${id}`
  );
  return mapOrganization(res.data ?? {});
};

export const createOrganization = async (payload: Record<string, any>) => {
  const data = {
    ...payload,
    addresses: serialiseAddresses(payload.addresses ?? [])
  };
  return http.request<ApiResponse<any>>("post", ORGANIZATION_BASE, {
    data
  });
};

export const updateOrganization = async (
  id: number | string,
  payload: Record<string, any>
) => {
  const data = {
    ...payload,
    addresses: serialiseAddresses(payload.addresses ?? [])
  };
  return http.request<ApiResponse<any>>("put", `${ORGANIZATION_BASE}/${id}`, {
    data
  });
};

export const deleteOrganization = async (id: number | string) => {
  return http.request<ApiResponse<boolean>>(
    "delete",
    `${ORGANIZATION_BASE}/${id}`
  );
};

export default {
  fetchList: fetchOrganizationList,
  fetchDetail: fetchOrganizationDetail,
  create: createOrganization,
  update: updateOrganization,
  remove: deleteOrganization
};
